import BTDecorator from '../../Base/BTDecorator'
import BTNode from '../../Base/BTNode'
import { NodeStatus } from '../../Enum'

export default class DecoratorRepeater extends BTDecorator {
  private repeatCount: number = Infinity
  private curCount: number = 0
  private endOnFailure: boolean = false

  constructor(childrens: BTNode[], repeatCount: number = Infinity, endOnFailure: boolean = false) {
    super(childrens)
    this.repeatCount = repeatCount
    this.endOnFailure = endOnFailure
  }

  canExecute(): boolean {
    return (
      this.curCount < this.repeatCount &&
      (!this.endOnFailure || (this.endOnFailure && this.status !== NodeStatus.Failure))
    )
  }
  onChildExecuted(status: NodeStatus): void {
    this.curCount++
    this.status = status
  }

  onStart() {
    super.onStart()
    this.curCount = 0
  }
}
